package com.springboot.mybatis.service.threaddemo;

/**
 * @author sunyt31481
 * @date 2020/8/7 10:28
 * @description 如果在执行过程中，每次循环都会调用sleep或wait等方法，则不需要每次迭代都检查是否已中断
 */
public class RightWayStopThreadWithSleepEveryLoop {
    public static void main(String[] args) {
        Runnable runnable = () -> {
            int num = 0;
            try {
                //由于每次迭代中都会调用sleep方法，所以会自动检测是否存在interrup，不需要在while中写!Thread.currentThread().isInterrupted()判断
                while (num <= 10000) {

                    if (num % 100 == 0) {
                        System.out.println(num + "是100的倍数");
                    }
                    num++;
                    //隔10毫秒打印一次，但是由于5000毫秒之后会有中断指令，所以只打印出了几个num
                    Thread.sleep(10);
                }
                Thread.sleep(1000);
                //同样捕获异常
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        //控制run内运行时间
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
    }
}
